from fastapi import FastAPI, Depends, HTTPException, status, Query
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List, Optional

from database import get_db, engine, Base
from models import User
from schemas import UserCreate, UserUpdate, User as UserSchema
from crud import get_user, get_users, create_user, update_user, delete_user

# 创建数据库表（异步）
async def create_tables():
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

app = FastAPI()

# 启动时创建表
@app.on_event("startup")
async def on_startup():
    await create_tables()

# 创建用户
@app.post("/users/", response_model=UserSchema, status_code=status.HTTP_201_CREATED)
async def create_user_endpoint(
    user: UserCreate, 
    db: AsyncSession = Depends(get_db)
):
    try:
        return await create_user(db, user)
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )

# 获取所有用户
@app.get("/users/", response_model=List[UserSchema])
async def read_users(
    skip: int = Query(0, ge=0, description="跳过记录数"),
    limit: int = Query(100, ge=1, le=1000, description="每页记录数"),
    db: AsyncSession = Depends(get_db)
):
    users = await get_users(db, skip=skip, limit=limit)
    return users

# 获取单个用户
@app.get("/users/{user_id}", response_model=UserSchema)
async def read_user(
    user_id: int, 
    db: AsyncSession = Depends(get_db)
):
    db_user = await get_user(db, user_id)
    if db_user is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="User not found"
        )
    return db_user

# 更新用户
@app.put("/users/{user_id}", response_model=UserSchema)
async def update_user_endpoint(
    user_id: int, 
    user: UserUpdate, 
    db: AsyncSession = Depends(get_db)
):
    db_user = await update_user(db, user_id, user)
    if db_user is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="User not found"
        )
    return db_user

# 删除用户
@app.delete("/users/{user_id}", response_model=UserSchema)
async def delete_user_endpoint(
    user_id: int, 
    db: AsyncSession = Depends(get_db)
):
    db_user = await delete_user(db, user_id)
    if db_user is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="User not found"
        )
    return db_user

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)